<script setup lang="ts">
import { DeleteFilled, Edit } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { getBrandByPage, deleteBatch, saveBrand, updateBrand } from '@/api/brand'
import { fa } from 'element-plus/es/locales.mjs'
import { findByStorageKey } from '@/utils/localStorageUtil'
import { ElMessage } from 'element-plus'

const currentPage4 = ref(1)
const pageSize4 = ref(10)
const size = ref(200)
const total = ref(400)
const disabled = false

const tableData = ref([])

const handleSizeChange = (e: any) => {
  console.log('handleSizeChange:', e)
}

const handleCurrentChange = (currentPage: number) => {
  currentPage4.value = currentPage
}

onMounted(async () => {
  getPageData()
})

const getPageData = async () => {
  const result = await getBrandByPage(currentPage4.value)
  tableData.value = result.data.records
  total.value = result.data.total
}

const selectable = (row: any) => row.id
const multipleSelection = ref([])
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}

const idList = ref<string[]>([])
const deleteBrand = (index: number, row: any) => {
  // 调用删除api
  idList.value.push(row.id.toString())
  deleteBatch(idList.value)
  getPageData()
  idList.value = []
}

const deleteBrandBatch = async (idList) => {
  idList.value = multipleSelection.value.map((item) => item.id)
  const result = await deleteBatch(idList.value)
  idList.value = []
  getPageData()
}

const dialogFrom = ref({
  id: null,
  brandName: '',
  logoUrl: '',
  brandStory: '',
  showStatus: 1
})

const saveOrUpdateBrand = (data) => {
  logTitle.value = '天机品牌'
  dialogFrom.value.brandName = ''
  dialogFrom.value.logoUrl = ''
  dialogVisible.value = true
}

const dialogVisible = ref(false)
const logTitle = ref('')

const cancle = () => {
  dialogVisible.value = false
}
const confirm = async () => {
  console.log(dialogFrom.value)
  if (!dialogFrom.value.logoUrl) {
    ElMessage.error(`文件上传失败，请稍后再试`)
  } else {
    let result
    if (dialogFrom.value.id) {
      result = await updateBrand(dialogFrom.value)
    } else {
      result = await saveBrand(dialogFrom.value)
    }
    if (result.code == 200) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      getPageData()
    }
  }
}

const accessToken = findByStorageKey('accessToken')
const uploadHeads = {
  accessToken
}

//图片上传成功的钩子函数
const handleAvatarSuccess = (res, file, files) => {
  if (res.code == 200) {
    dialogFrom.value.logoUrl = res.data
  } else {
    ElMessage.error(`文件上传失败,{}`, res.message)
  }
}
const allowFileType = ['image/jpeg', 'image/png']

//上传图片之前钩子函数： 检验文件大小和格式
const beforeAvatarUpload = (rawFile) => {
  if (!allowFileType.includes(rawFile.type)) {
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const editBrand = (rowFile: any) => {
  logTitle.value = '编辑品牌'
  console.log(rowFile)
  // Object.assign(dialogFrom, rowFile)
  dialogFrom.value.id = rowFile.id
  dialogFrom.value.brandName = rowFile.brandName
  dialogFrom.value.logoUrl = rowFile.logoUrl

  dialogVisible.value = true
}
</script>

<template>
  <div class="brand_container">
    <el-card>
      <!-- 按钮区域 -->
      <div class="button_header">
        <el-button type="primary" :icon="Edit" @click="saveOrUpdateBrand">添加品牌</el-button>
        <el-button type="danger" :icon="Edit" @click="deleteBrandBatch">批量删除</el-button>
      </div>
      <!-- 列表展示区域 -->
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="selectable" width="55" label="选择">
        </el-table-column>
        <el-table-column prop="id" label="序号" width="100" />
        <el-table-column prop="brandName" label="品牌名称" width="180" />
        <el-table-column  label="是否显示" width="180" >
          <template #default="scope">
            <span>{{scope.row.showStatus?'显示':'不显示'}}</span>
            <el-switch
              v-model="scope.row.showStatus"
              inline-prompt
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌图标" width="190">
          <template #default="scope">
            <el-image style="width: 50px; height: 50px" :src="scope.row.logoUrl" fit="contain">
              <template #error>
                <div class="image-slot">
                  <el-icon :size="40"><Picture /></el-icon>
                </div> </template
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="editBrand(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteBrand(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页选择器 -->
      <template #footer>
        <el-pagination
          v-model:current-page="currentPage4"
          v-model:page-size="pageSize4"
          :size="size"
          :disabled="disabled"
          layout="total, prev, pager, next,->, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </template>
    </el-card>

    <!--  对话框-->
    <el-dialog v-model="dialogVisible" :title="logTitle" width="500" :before-close="handleClose">
      <el-form label-width="80px">
        <el-form-item label="品牌名称">
          <el-input
            placeholder="输入品牌名称"
            type="text"
            v-model="dialogFrom.brandName"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <!--上传组件-->
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/file/upload"
            method="post"
            :headers="uploadHeads"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="dialogFrom.logoUrl" :src="dialogFrom.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon" :size="40"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="品牌故事">
          <textarea v-model="dialogFrom.brandStory"></textarea>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="dialogFrom.showStatus">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancle">取消</el-button>
          <el-button type="primary" @click="confirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 98px;
  height: 98px;
  text-align: center;
}
</style>
